import { useState, useEffect } from 'react';

export const Parent = () => {
  const [count, setCount] = useState(0);
  // 组件渲染完毕后执行一个副作用
  return (
    <div>
      <h2>组件只在渲染完毕后执行一次Effect</h2>
      <h2>{count}</h2>
      <button onClick={() => setCount(count + 1)}>+1</button>
      {count > 3 ? null : <Child />}
    </div>
  );
};

export const Child = () => {
  // 组件渲染完毕后执行一个副作用
  useEffect(() => {
    console.log('Child组件渲染完毕后执行');
    const timerId = setInterval(() => {
      console.log('我是子组件开启的计时器');
    }, 500);
    return () => {
      console.log('Child我会在组件卸载后执行');
      clearInterval(timerId);
    };
  }, []);

  return (
    <div style={{ border: '1px solid red', margin: 48 }}>
      <h2>Child</h2>
    </div>
  );
};
